package com.eascs.archive.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eascs.admin.o2o.loan.dao.O2oLoanapplyDao;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.archive.dao.ArchiveRecordDao;
import com.eascs.archive.entity.ArchiveRecordEntity;
import com.eascs.archive.entity.FieldEntity;
import com.eascs.archive.service.ArchiveRecordService;
import com.eascs.archive.service.ArchiveService;
import com.eascs.archive.untils.ArchiveConstants;
import com.eascs.common.doc.excel.ExcelApiHelper;
import com.eascs.common.doc.excel.RowReadHandler;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@RestController
@RequestMapping("/archive/import/rest")
public class ArchiveImportController extends BaseRestController {

	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ArchiveService archiveService;
	@Autowired
	private ArchiveRecordService archiveRecordService;
	@Autowired
	private O2oLoanapplyDao o2oLoanapplyDao;
	@Autowired
	private ArchiveRecordDao archiveRecordDao;
	
	private final static String creator="admin";
	
	/**终端贷数据导入（中行、村镇）*/
	@RequestMapping("/terminal")
	@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> uploadBankExcel(@RequestParam(value = "file", required = false) MultipartFile file) {
		User user = UserHolder.getUser();
		String loanerName = user.getCname();
		logger.info("------------开始导入终端贷款归档数据,user:{}--------------",loanerName);
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			if (!".xls".equals(suffix)) {
				logger.info("-----文件类型不对");
				return BaseRestResult.warn("文件类型不对");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		ExcelApiHelper.readHandle(inputStream, new RowReadHandler() {
			@Override
			public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
				try {
					caclRow(sheetIndex, rowIndex, rowDatas, 0, loanerName);
				} catch (Exception e) {
					logger.info("-----数据处理失败，第[{}]行,rowData:[{}]",rowIndex,JSON.toJSONString(rowDatas));
				}
			}
		});
		logger.info("------------结束导入终端贷款归档数据--------------");
		return BaseRestResult.buildClosestReloadResult();
	}
	
	
	/**接力贷分期贷 归档数据导入（EA）*/
	@RequestMapping("/ea")
	@Transactional(transactionManager = "o2oTransactionManager")
	public BaseRestResult<String> uploadEaExcel(@RequestParam(value = "file", required = false) MultipartFile file) {
		User user = UserHolder.getUser();
		String loanerName = user.getCname();
		logger.info("------------开始导入终端贷款归档数据,user:{}--------------",loanerName);
		InputStream inputStream = null;
		try {
			inputStream = file.getInputStream();
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			if (!".xls".equals(suffix)) {
				logger.info("-----文件类型不对");
				return BaseRestResult.warn("文件类型不对");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Map<String,String> fileds=new LinkedHashMap<>();
		ExcelApiHelper.readHandle(inputStream, new RowReadHandler() {
			@Override
			public void handle(int sheetIndex, int rowIndex, Object[] rowDatas) {
				try {
					caclEaRow(sheetIndex, rowIndex, rowDatas, 0, loanerName,fileds);
				} catch (Exception e) {
					logger.info("-----数据处理失败，第[{}]行,rowData:[{}]",rowIndex,JSON.toJSONString(rowDatas));
				}
			}
		});
		logger.info("------------结束导入终端贷款归档数据--------------");
		return BaseRestResult.buildClosestReloadResult();
	}
	
	private boolean caclEaRow(int sheetIndex, int rowIndex, Object[] rowDatas, int type, String name,Map<String,String> fileds) {
		logger.info("-----正在读取第[{}]行,rowData:[{}]",rowIndex,JSON.toJSONString(rowDatas));
		fileds = getData(sheetIndex, rowIndex, rowDatas, fileds);
		logger.info("-----存柜资料:[{}]",JSON.toJSONString(fileds));
		if (rowIndex <= 1) {
			logger.info("-----跳过表头");
			return false;
		}
		String cabinet_no = isBlank(rowDatas[0]+"");
		String loan_name = String.valueOf(rowDatas[1] == null ? "" : rowDatas[1]);
		String billCode = String.valueOf(rowDatas[2] == null ? "" : rowDatas[2]);
		String archive_no = String.valueOf(rowDatas[3] == null ? "" : rowDatas[3]);
		String archive_date = String.valueOf(rowDatas[10] == null ? "" : rowDatas[10]);
		
		if(StringUtils.isBlank(billCode)){
			logger.info("-----数据异常,贷款编号不能为空");
			return false;
		}
		
		O2oLoanapplyEntity loanInfo =o2oLoanapplyDao.queryBillCode(billCode);
		if (loanInfo == null) {
			logger.info("-----根据贷贷款编号:[{}]，未找到贷款单数据",billCode);
			return false;
		}
		
		String loanapplyNo=loanInfo.getLoanapplyNo();
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		logger.info("-----获取贷款单信息no：[{}]",loanapplyNo);
		if (!StringUtils.equals(bankName, "EA") ) {
			logger.info("-----贷款单放款银行不是EA银行");
			return false;
		}
		
		Date createTime=null;
		try {
			createTime = new SimpleDateFormat("yyyy-MM-dd").parse(archive_date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		List<FieldEntity> cabinetFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
		JSONObject cabinetJson = JSONObject.parseObject("{}");
		for (FieldEntity f : cabinetFields) {
			String val=fileds.get(f.getFieldName());
			if(StringUtils.isBlank(val))
				val=f.getFieldMin()+"";
			cabinetJson.put(f.getFieldName(), val);
		}
		
		String financeJson="{\"合作协议\":\"1\"}";
		String archiveInfoJson=cabinetJson.toJSONString();
		String bankInfoJson="{}";
		
		save(loanInfo,financeJson,archiveInfoJson,bankInfoJson,createTime,cabinet_no,archive_no);
		return true;
	}
	
	
	
	private boolean caclRow(int sheetIndex, int rowIndex, Object[] rowDatas, int type, String name) {
		logger.info("-----正在读取第[{}]行,rowData:[{}]",rowIndex,JSON.toJSONString(rowDatas));
		if (rowIndex <= 1) {
			logger.info("-----跳过表头");
			return false;
		}
		
		String cabinet_no = isBlank(rowDatas[0]+"");
		String archive_no = String.valueOf(rowDatas[1] == null ? "" : rowDatas[1]);
		String loan_name = String.valueOf(rowDatas[2] == null ? "" : rowDatas[2]);
		String loan_money = String.valueOf(rowDatas[3] == null ? "" : rowDatas[3]);
		String loan_date = String.valueOf(rowDatas[4] == null ? "" : rowDatas[4]);
		
		if (StringUtils.isBlank(loan_name) && StringUtils.isBlank(loan_date)) {
			logger.info("-----数据异常");
			return false;
		}
		
		Date loanDate=null;
		try {
			loanDate = new SimpleDateFormat("yyyy年MM月dd日").parse(loan_date);
		} catch (ParseException e) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				loanDate = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(Double.valueOf(loan_date));
				logger.info("-----excel放款日期转化[{}]-->[{}]",loan_date,sdf.format(loanDate));
			} catch (Exception e2) {
				e.printStackTrace();
			}
		}
		
		O2oLoanapplyEntity loanInfo =o2oLoanapplyDao.queryLoanByUserAndLoanDate(loan_name, loanDate);
		if (loanInfo == null) {
			logger.info("-----根据贷款用户和放款时间，未找到贷款单数据");
			return false;
		}
		
		logger.info("-----获取贷款单信息no：[{}]",loanInfo.getLoanapplyNo());
		if (!StringUtils.equals(loanInfo.getBankLoanName(), "BC") && !StringUtils.equals(loanInfo.getBankLoanName(), "GACZ")) {
			logger.info("-----贷款单放款银行不是中国银行或者国安村镇银行");
			return false;
		}
		
		
		String financeJson="{\"合作协议\":\"1\"}";
		String archiveInfoJson="{\"借款借据\":\"3\",\"借款合同\":\"1\",\"无限连带责任书（自然人与企业版）\":\"2\"}";
		String bankInfoJson="{}";
		
		
		Date createTime=null;
		try {
			createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse("2017-03-09 19:48");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		if (StringUtils.isNotBlank(bankTypeId)) {
			List<FieldEntity> bankFields = archiveService.getFieldListByType(bankTypeId, ArchiveConstants.FORMTYPE_BANK);
			JSONObject bankJson = JSONObject.parseObject("{}");
			for (FieldEntity f : bankFields) {
				bankJson.put(f.getFieldName(), f.getFieldMin());
			}
			bankInfoJson = bankJson.toJSONString();
		}
		save(loanInfo,financeJson,archiveInfoJson,bankInfoJson,createTime,cabinet_no,archive_no);
		
		return true;
	}
	
	private boolean save(O2oLoanapplyEntity loanInfo,String financeJson,String archiveInfoJson,String bankInfoJson,Date createTime,String cabinet_no,String archive_no){
		String loanapplyNo=loanInfo.getLoanapplyNo();
		String bankName = loanInfo.getBankLoanName();
		String bankTypeId = ArchiveConstants.getBankTypeId(bankName);
		
		List<ArchiveRecordEntity> record=archiveRecordDao.queryArchiveRecordByLoanapplyNo(loanapplyNo);
		if(record.size() > 0){
			logger.info("-----该条数据导入无效，贷款单已经完成归档");
			return false;
		}
		
		ArchiveRecordEntity finance=new ArchiveRecordEntity();
		finance.setLoanapplyNo(loanapplyNo);
		finance.setBankTypeId(bankTypeId);
		finance.setFormTypeId(ArchiveConstants.FORMTYPE_FINANCE);
		finance.setContentJson(financeJson);
		finance.setCreator(creator);
		finance.setUpdator(creator);
		finance.setCreateTime(createTime);
		finance.setUpdateTime(createTime);
		archiveRecordService.insertArchiveRecord(finance);
		logger.info("-----财务行归档表单保存成功");
		
		ArchiveRecordEntity archive=new ArchiveRecordEntity();
		archive.setLoanapplyNo(loanapplyNo);
		archive.setBankTypeId(bankTypeId);
		archive.setFormTypeId(ArchiveConstants.FORMTYPE_ARCHIVE_INFO);
		archive.setContentJson(archiveInfoJson);
		archive.setCreator(creator);
		archive.setUpdator(creator);
		archive.setCreateTime(createTime);
		archive.setUpdateTime(createTime);
		archive.setArchiveNo(archive_no);
		archive.setCabinetNo(cabinet_no);
		archiveRecordService.insertArchiveRecord(archive);
		logger.info("-----存柜资料表单保存成功");
		
		
		ArchiveRecordEntity bank=new ArchiveRecordEntity();
		bank.setLoanapplyNo(loanapplyNo);
		bank.setBankTypeId(bankTypeId);
		bank.setFormTypeId(ArchiveConstants.FORMTYPE_BANK);
		bank.setContentJson(bankInfoJson);
		bank.setCreator(creator);
		bank.setUpdator(creator);
		bank.setCreateTime(createTime);
		bank.setUpdateTime(createTime);
		archiveRecordService.insertArchiveRecord(bank);
		logger.info("-----银行归档表单保存成功");
		return true;
	}
	
	private Map<String,String>  getData(int sheetIndex, int rowIndex, Object[] rowDatas,Map<String,String> fileds){
		if (rowIndex <= 0) {
			return fileds;
		}
		String field_1 = String.valueOf(rowDatas[11] == null ? "" : rowDatas[11]);
		String field_2 = String.valueOf(rowDatas[12] == null ? "" : rowDatas[12]);
		String field_3 = String.valueOf(rowDatas[13] == null ? "" : rowDatas[13]);
		String field_4 = String.valueOf(rowDatas[14] == null ? "" : rowDatas[14]);
		String field_5 = String.valueOf(rowDatas[15] == null ? "" : rowDatas[15]);
		String field_6 = String.valueOf(rowDatas[16] == null ? "" : rowDatas[16]);
		String field_7 = String.valueOf(rowDatas[17] == null ? "" : rowDatas[17]);
		String field_8 = String.valueOf(rowDatas[18] == null ? "" : rowDatas[18]);
		String field_9 = String.valueOf(rowDatas[19] == null ? "" : rowDatas[19]);
		String field_10 = String.valueOf(rowDatas[20] == null ? "" : rowDatas[20]);
		String field_11 = String.valueOf(rowDatas[21] == null ? "" : rowDatas[21]);
		String field_12 = String.valueOf(rowDatas[22] == null ? "" : rowDatas[22]);
		String field_13 = String.valueOf(rowDatas[23] == null ? "" : rowDatas[23]);
		String field_14 = String.valueOf(rowDatas[24] == null ? "" : rowDatas[24]);
		String field_15 = String.valueOf(rowDatas[25] == null ? "" : rowDatas[25]);
		String field_16 = String.valueOf(rowDatas[26] == null ? "" : rowDatas[26]);
		String field_17 = String.valueOf(rowDatas[27] == null ? "" : rowDatas[27]);
		String field_18 = String.valueOf(rowDatas[28] == null ? "" : rowDatas[28]);
		String field_19 = String.valueOf(rowDatas[29] == null ? "" : rowDatas[29]);
		String field_20 = String.valueOf(rowDatas[30] == null ? "" : rowDatas[30]);
		String field_21 = String.valueOf(rowDatas[31] == null ? "" : rowDatas[31]);
		String field_22 = String.valueOf(rowDatas[32] == null ? "" : rowDatas[32]);
		String field_23 = String.valueOf(rowDatas[33] == null ? "" : rowDatas[33]);
		String field_24 = String.valueOf(rowDatas[34] == null ? "" : rowDatas[34]);
		String field_25 = String.valueOf(rowDatas[35] == null ? "" : rowDatas[35]);
		if(rowIndex == 1){
			String val="0";
			fileds.put(field_1, val);
			fileds.put(field_2, val);
			fileds.put(field_3, val);
			fileds.put(field_4, val);
			fileds.put(field_5, val);
			fileds.put(field_6, val);
			fileds.put(field_7, val);
			fileds.put(field_8, val);
			fileds.put(field_9, val);
			fileds.put(field_10, val);
			fileds.put(field_11, val);
			fileds.put(field_12, val);
			fileds.put(field_13, val);
			fileds.put(field_14, val);
			fileds.put(field_15, val);
			fileds.put(field_16, val);
			fileds.put(field_17, val);
			fileds.put(field_18, val);
			fileds.put(field_19, val);
			fileds.put(field_20, val);
			fileds.put(field_21, val);
			fileds.put(field_22, val);
			fileds.put(field_23, val);
			fileds.put(field_24, val);
			fileds.put(field_25, val);
		}else{
			Set<String> keys=fileds.keySet();
			Iterator<String> it=keys.iterator();
			fileds.put(it.next(),isBlank(field_1));
			fileds.put(it.next(),isBlank(field_2));
			fileds.put(it.next(),isBlank(field_3));
			fileds.put(it.next(),isBlank(field_4));
			fileds.put(it.next(),isBlank(field_5));
			fileds.put(it.next(),isBlank(field_6));
			fileds.put(it.next(),isBlank(field_7));
			fileds.put(it.next(),isBlank(field_8));
			fileds.put(it.next(),isBlank(field_9));
			fileds.put(it.next(),isBlank(field_10));
			fileds.put(it.next(),isBlank(field_11));
			fileds.put(it.next(),isBlank(field_12));
			fileds.put(it.next(),isBlank(field_13));
			fileds.put(it.next(),isBlank(field_14));
			fileds.put(it.next(),isBlank(field_15));
			fileds.put(it.next(),isBlank(field_16));
			fileds.put(it.next(),isBlank(field_17));
			fileds.put(it.next(),isBlank(field_18));
			fileds.put(it.next(),isBlank(field_19));
			fileds.put(it.next(),isBlank(field_20));
			fileds.put(it.next(),isBlank(field_21));
			fileds.put(it.next(),isBlank(field_22));
			fileds.put(it.next(),isBlank(field_23));
			fileds.put(it.next(),isBlank(field_24));
			fileds.put(it.next(),isBlank(field_25));
		}
		return fileds;
	}
	
	private String isBlank(String filed){
		return StringUtils.isBlank(filed)? "" :(Float.valueOf(filed).intValue()+"");
	}
	
}
